package com.orange.cepmanagerweb.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.orange.cepmanagerweb.dao.iface.IPhoneDAO;
import com.orange.cepmanagerweb.model.Phone;

@Repository
public class PhoneDAO implements IPhoneDAO {

	private HibernateTemplate hibernateTemplate;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	@Autowired
	private SessionFactory sessionFactory;

	public Phone getById(int id) {
		return (Phone) sessionFactory.getCurrentSession().get(Phone.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Phone> getPhones() {
		return hibernateTemplate.find("from Phone");
	}

	@Override
	public void deletePhone(String id) {
		Object record = hibernateTemplate.load(Phone.class, id);
		hibernateTemplate.delete(record);
	}

	@Override
	public Phone savePhone(Phone phone) {
		hibernateTemplate.saveOrUpdate(phone);
		return phone;
	}

	@Override
	public List<Phone> searchPhones(String name) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
				Phone.class);
		criteria.add(Restrictions.ilike("name", name + "%"));
		return criteria.list();
	}
}
